package algotithm.leetcode.presum.test1074;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 25068
 * @Date 2021/5/29 9:45
 * @Title 1074. 元素和为目标值的子矩阵数量
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] matrix = {{0,1,0},{1,1,1},{0,1,0}};
        int target = 0;
        int sum = solution.numSubmatrixSumTarget(matrix, target);
        System.out.println(sum);
    }

    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int ans = 0;
        int m = matrix.length, n = matrix[0].length;
        // 枚举上边界
        for (int i = 0; i < m; ++i) {
            int[] sum = new int[n];
            // 枚举下边界
            for (int j = i; j < m; ++j) {
                // 更新每列的元素和
                for (int c = 0; c < n; ++c) {
                    sum[c] += matrix[j][c];
                }
                ans += subarraySum(sum, target);
            }
        }
        return ans;
    }

    public int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, 1);
        int count = 0, pre = 0;
        for (int x : nums) {
            pre += x;
            if (map.containsKey(pre - k)) {
                count += map.get(pre - k);
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
